package com.example.micro.netty.server.nio.channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 用一个ByteBuffer进行文件拷贝
 */
public class NIOFileCopyChannelDemo {

    public static void main(String[] args) throws IOException {

        FileInputStream fileInputStream = new FileInputStream("/Users/didi/IdeaProjects/nio_file_demo1.txt");
        FileChannel readChannel = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("/Users/didi/IdeaProjects/nio_file_demo1_copy.txt");
        FileChannel writeChannel = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(5);

        while (true) {
            //清空byteBuffer，并重置为写模式
            byteBuffer.clear();
            //从通道读取数据到byteBuffer中，若没有数据，read为-1
            int read = readChannel.read(byteBuffer);
            if (read == -1) {
                break;
            }
            //切换为读模式
            byteBuffer.flip();
            writeChannel.write(byteBuffer);
        }

        fileInputStream.close();
        fileOutputStream.close();
    }

}
